local cjson = require("cjson")
local redis = require("resty.redis")
local ngx_log = ngx.log
local ngx_ERR = ngx.ERR
-- 关闭redis连接
local function close_redis(red)
    if not red then
        return
    end
    local pool_max_idle_time = 10000 --毫秒
    local pool_size = 100 --连接池大小
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)

    if not ok then
        ngx_log(ngx_ERR, "set redis keepalive error : ", err)
    end
end
-- 根据key读取redis，如果是一个key使用get，如果是一个table使用的就是mget
local function read_redis(ip, port, keys)
    local red = redis:new()
    red:set_timeout(1000)
    local ok, err = red:connect(ip, port)
    if not ok then
        ngx_log(ngx_ERR, "connect to redis error : ", err)
        return close_redis(red)
    end
    local resp = nil
    if #keys == 1 then
        resp, err = red:get(keys[1])
    else
        resp, err = red:mget(keys)
    end
    if not resp then
        ngx_log(ngx_ERR, "get redis content error : ", err)
        return close_redis(red)
    end

    if resp == ngx.null then
        resp = nil
    end
    close_redis(red)

    return resp
end

-- 查询IP是否在黑名单
local function has_black_list( ip ,port, key )
    local red = redis:new()
    local ok, err = red:connect(ip, port)
    if not ok then
        ngx_log(ngx_ERR, "connect to redis error : ", err)
        return close_redis(red)
    end
    local resp,err = red:sismember("blacklist",key[1])
    if not resp then 

    	ngx_log(ngx_ERR, "read blacklist set error : ", err)
        return close_redis(red)
    end
    close_redis(red)
    return resp

end

-- url白名单
local function white_list( ip ,port)
      local red = redis:new()
      local ok, err = red:connect(ip, port)
      if not ok then
          ngx_log(ngx_ERR, "connect to redis error : ", err)
          return close_redis(red)
      end
      local resp,err = red:SMEMBERS("url_white_list")
      if not resp then
          ngx_log(ngx_ERR, "read whitelist  error : ", err)
          return close_redis(red)
      end
    	close_redis(red)
      return resp
 end 

-- 获取用户真实IP
local function real_ip()
     local ip = ngx.req.get_headers()["X-Real-IP"]
     if ip == nil then
        ip = ngx.req.get_headers()["x_forwarded_for"]
     end
     if ip == nil then
        ip =  ngx.var.remote_addr
     end
     return ip

end

-- 统一错误结构
local function error_msg(code,msg)
    return cjson.encode({code = code,msg = msg})
end

--redis配置
local redis_config = {
    ip = "127.0.0.1",
    port = 6379
}

local _M = {
    read_redis = read_redis,
    has_black_list = has_black_list,
    real_ip=real_ip,
    error_msg=error_msg,
    redis_config = redis_config,
    white_list = white_list
}
return _M
